package com.maserb.monitor.dataCenter.handler;

import com.maserb.monitor.dataCenter.communication.EigenValue;
import com.maserb.monitor.dataCenter.communication.EigenWarningStatusEnum;
import com.maserb.monitor.dataCenter.communication.WaveNetPackage;
import com.maserb.monitor.entity.EigenValueEntity;
import com.maserb.monitor.entity.WaveEntity;
import com.maserb.monitor.repository.EigenValueRepository;
import com.maserb.monitor.repository.WaveRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
public class WaveRepositoryHandler {
    private ExecutorService fixedThreadPool = Executors.newFixedThreadPool(4);

    @Autowired
    private EigenValueRepository eigenValueRepository;

    @Autowired
    private AlarmRepositoryHandler alarmRepositoryHandler;

    @Autowired
    private WaveRepository waveRepository;

    public void publish(WaveNetPackage response) {
        fixedThreadPool.execute(() -> {
            try {
                EigenValueEntity entity = new EigenValueEntity();
                entity.setDeviceCode(response.getDeviceCode());
                entity.setPointCode(response.getPointCode());
                entity.setSampleTime(new Date(response.getEigenValueTime().toDate().getTime()));
                List<EigenWarningStatusEnum> statuses = new LinkedList<>();
                for (int i = 0; i < response.getEigenValueList().size(); i++) {
                    EigenValue ev = response.getEigenValueList().get(i);
                    entity.setValueAndStatusX(i, ev.getValueType(), ev.getWarningStatusEnum(), ev.getEigenValue());
                    statuses.add(ev.getWarningStatusEnum());
                }
                eigenValueRepository.save(entity, response.getDeviceCode());
                alarmRepositoryHandler.publish(entity, statuses, response.getDeviceCode());

                WaveEntity waveEntity = new WaveEntity();
                waveEntity.setDeviceCode(response.getDeviceCode());
                waveEntity.setPointCode(response.getPointCode());
                waveEntity.setSampleFrequence(response.getSampleFrequence());
                waveEntity.setData(response.getWaveData());
                waveEntity.setSampleTime(new Date(response.getWaveBeginTime().toDate().getTime()));
                waveRepository.save(waveEntity, response.getDeviceCode());

            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
}
